package com.dd.framework.config;

import com.alibaba.fastjson.JSONObject;
import com.dd.framework.jwt.JwtUserDetailsService;
import com.dd.framework.security.component.DynamicSecurityService;
import com.dd.framework.security.config.IgnoreUrlsConfig;
import com.dd.framework.security.config.SecurityConfig;
import com.dd.framework.security.jwt.property.JwtTokenConfig;
import com.dd.web.base.entity.data.UmsMenu;
import com.dd.web.base.service.UmsMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Configuration
@EnableWebSecurity  // 这个注解必须加，开启Security
@EnableGlobalMethodSecurity(prePostEnabled = true)//保证post之前的注解可以使用
@EnableConfigurationProperties({JwtTokenConfig.class,IgnoreUrlsConfig.class})
public class WebSecurityConfig extends SecurityConfig {


    @Autowired
    private JwtTokenConfig jwtTokenConfig;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private UmsMenuService resourceService;

    @Override
    public JwtTokenConfig jwtTokenConfig() {
        return this.jwtTokenConfig;
    }

    @Override
    public UserDetailsService userDetailsService() {
        return this.jwtUserDetailsService;
    }

    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return new DynamicSecurityService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {
                Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
                List<UmsMenu> resourceList = resourceService.listAll();
                log.debug("读取所有资源地址对应角色"+JSONObject.toJSONString(resourceList));
                for (UmsMenu resource : resourceList) {
                    map.put(resource.getPath(), new org.springframework.security.access.SecurityConfig(resource.getId()+""));
                }
                return map;
            }
        };
    }
}
